package com.clusterswisdom.horn.api.ioc.api;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Element;

public class RequestConfig implements Serializable {

	private static final long serialVersionUID = -7205143553520829235L;

	private ParamParser parser;
	
	private List<RequestParam> params;
	
	public RequestConfig(Element element) {
		this.parser = getParamParser(element);
		this.params = getParams(element);
	}
	
	public ParamParser getParser() {
		return parser;
	}

	public List<RequestParam> getParams() {
		return params;
	}

	@SuppressWarnings("unchecked")
	private List<RequestParam> getParams(Element element) {
		Iterator<Element> paramIterator = element.elementIterator("param");
	    List<RequestParam> requests = new ArrayList<RequestParam>();
	    
		while (paramIterator.hasNext()) {
	    	Element paramElement = paramIterator.next();
	    	requests.add(new RequestParam(paramElement));
	    }

		return requests;
	}
	
	private ParamParser getParamParser(Element element) {
		String parserValue = element.attributeValue("parser");
		if (parserValue == null || parserValue.trim().length() == 0) {
			return null;
		}
		
		try {
			return (ParamParser)Thread.currentThread().getContextClassLoader().loadClass(parserValue).newInstance();
			
		} catch (Exception e) {
			e.printStackTrace();
			return null;
			
		}
	}
}